package com.example.entity;

/**
 * 自定义尝试从0开始实现环形队列
 * 证明从0还是从-1开始，实际上只影响操作的顺序，并不影响环形队列的实现。关键在于首位之间需要空出一位
 * 从0开始：先操作后移位，front在第一个元素上，rear在最后一个元素后一位
 * 从-1开始：先移位后操作，front在第一个元素之前一位，rear在最后一个元素上
 *
 * @Author: wanqian
 * @Date: 2021/1/22 14:51
 */
public class CircleArrayCustom {
    private int maxSize;

    private int front = 0;

    private int rear = 0;

    private int[] arr;

    public CircleArrayCustom(int maxSize) {
        this.maxSize = maxSize + 1;
        this.arr = new int[this.maxSize];
    }

    public void addQueue(int i) {
        if (isFull()) {
            System.out.println("队列已满");
            return;
        }
        arr[rear] = i;
        rear = (rear + 1) % maxSize;
    }

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int i = arr[front];
        this.front = (front + 1) % maxSize;
        return i;
    }

    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空");
            return;
        }
//        for (int i = front; i != front; i = (i + 1) % maxSize) {
//            System.out.println(String.format("arr[%d] = %d", i, arr[i]));
//        }
        int size = size();
        for (int i = front; i < front + size; i++) {
            System.out.println(String.format("arr[%d] = %d", i % maxSize, arr[i % maxSize]));
        }
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty() {
        return rear == front;
    }


    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }

    public int size() {
        //自行领悟
        return (rear + maxSize - front) % maxSize;
    }
}
